<script setup lang="ts">
import {reactive, defineProps, onUpdated, ref} from "vue";
import request from "@/utils/request.ts";
import {ElMessage, ElMessageBox, type FormInstance, type UploadProps} from "element-plus";
const editForm = ref<FormInstance | null>(null)
const data = reactive({
  goods: [] as any[],
  rules: {
    name: [
      {required: true, message: '请输入物品名称', trigger: 'blur'},
    ],
    classification: [
      { required: true, message: '请输入物品分类', trigger: 'blur' },
      { max: 50, message: '分类名称不能超过50个字符', trigger: 'blur' }
    ],
    number: [
      { required: true, message: '请输入物品数量', trigger: 'blur' },
      { pattern: /^\d+$/, message: '数量必须为数字', trigger: 'blur' },
    ],
    endtime: [
      { required: true, message: '请选择结束时间', trigger: 'blur' },
    ],
    degree: [
      { required: true, message: '请输入重要程度', trigger: 'blur' },
      { pattern: /^[1-3]$/,max:1, message: '程度分3级，请输入数字级别', trigger: 'blur' },
    ],
  },
  options: [
    {
      value: '0',
      label: '卧室',
    },
    {
      value: '1',
      label: '书房',
    },
    {
      value: '2',
      label: '厨房',
    },
    {
      value: '3',
      label: '客厅',
    },
    {
      value: '4',
      label: '餐厅',
    },
    {
      value: '5',
      label: '卫生间',
    },
    {
      value: '6',
      label: '浴室',
    },
    {
      value: '7',
      label: '阳台',
    },
    {
      value: '8',
      label: '储物间',
    },
    {
      value: '9',
      label: '衣帽间',
    },

  ],
})

//父传子  通过<router-view goodList:data.goodList/>将父组件获得的数据放置data.goodList里 然后通过goodList传给子组件
// 假设父组件通过 props 传递商品列表
const props = defineProps({
  goodList: {
    type: Array,
    default: () => [] as any[]
  },
  total:'',
});
// 监听 props 变化，更新本地列表
onUpdated(() => {
  if (props.goodList) {
    data.goods = props.goodList;
  }
});
// 从父组件获取重新加载数据的方法（关键：通过回调通知父组件刷新）
const emit = defineEmits(['refreshGoods']);
function del(goodid: string) {
  ElMessageBox.confirm("确定删除？", "删除操作", { type: "warning" }).then(() => {
        request.delete(`/deleteGoods/${goodid}`).then(res => {
              if (res.status === '200') { // 兼容后端响应格式
                ElMessage.success("删除成功");
                // 关键：通知父组件重新请求数据（父组件实现刷新逻辑）
                emit('refreshGoods');
              } else {
                ElMessage.error("删除失败：" + (res.msg || '未知错误'));
              }
            }).catch(err => {
              ElMessage.error("删除请求失败，请重试");
              console.error(err);
            });
      }).catch(() => {
        // 用户取消删除
        ElMessage.info("已取消删除");
      });
}
function update(goodid: string,number1: number) {
  request.put(`/updateGoods/${goodid}`, null,{
    params: {
      number: number1,
    }
  }).then(res => {
    // console.log("数量更新结果：", res);
    if (res.status === '200') { // 按后端实际响应格式调整
      // 4. 关键：重新获取数据，确保前端显示与后端同步
      emit('refreshGoods');
    } else {
      ElMessage.error(res.msg );
    }
  })
}
// 处理编辑按钮点击，翻转卡片
function handleEdit(item:any,event:Event) {
  // 保存原始数据用于取消编辑时恢复
  item.originalData = { ...item };
  item.isEditing = true;
  /*
  //原始的js获取按钮对象 修改样式
  const cart1 = event.target.parentNode.parentNode.parentNode;
  cart1.style.display="none";
  //获取兄弟元素对象 修改样式
  const cart2 =cart1.nextElementSibling;
  cart2.style.display = "block";
   */

}
// 取消编辑，翻转回正面
function cancelEdit(item:any) {
  // 恢复原始数据
  Object.assign(item, item.originalData);
  delete item.originalData;
  item.isEditing = false;

}
// 保存编辑
function saveEdit(item:any) {
  editForm.value.validate( (valid:boolean) => {//需要验证
    if (valid) {
      if (!(item.starttime <= item.endtime)) {
        ElMessage.error("结束时间必须晚于开始时间")
      } else {
        request.put("/updateGoods", item).then(res => {
              if (res.status === '200') {
                emit('refreshGoods');
                // 保存成功后翻转回正面
                item.isEditing = false;
                ElMessage.success('修改成功');
              } else {
                ElMessage.error(res.msg);
              }
            }
        )
      }
    }
  })
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile,item:any) => {
  //imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  console.log(response)
  item.image = response.data;//获取服务器返回的图片可访问路径
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!(rawFile.type === 'image/jpeg' || rawFile.type === 'image/png')) {
    ElMessage.error('Avatar picture must be JPG Or PNG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
</script>
<template>
  <div class="card-list-container">
    <div class="flip-container"
         :class="{ flipper: item.isEditing }"
         v-for="(item, index) in data.goods"
         :key="item.goodid !== undefined ? item.goodid : index"
    >
      <div class="flipper">
        <el-card class="data-card" shadow="hover" v-if="!item.isEditing">
          <div style="justify-self:end;">
            <button @click="handleEdit(item,$event)" style="background: #02e5ff;height: 25px;border-radius: 10px">
              <el-icon><EditPen /></el-icon>
            </button>
            <button @click="del(item.goodid)" style="background: #de3f3f;height: 25px;border-radius: 10px">
              <el-icon ><CloseBold /></el-icon>
            </button>
          </div>
          <div class="card-content">
            <div class="avatar-degree-group">
              <el-image
                  v-if="item.image"
                  :src="`http://localhost:8080${item.image}`"
                  :preview-src-list="[`http://localhost:8080${item.image}`]"
                  :preview-teleported="true"
                  class="avatar"
              />
              <el-icon v-else class="default-avatar"><Goods /></el-icon>
              <div class="degree-info">
                <span class="label">程度：</span>
                <el-icon
                    v-for="(star, index) in (item.degree ? Number(item.degree) : 1)"
                    key="index"
                    class="star-icon"
                >
                  <StarFilled />
                </el-icon>
              </div>
            </div>
            <div class="data-info">
              <div class="info-row">
                <span class="label">名称：</span>
                <span class="value">{{ item.name}}</span>
              </div>
              <div class="info-row">
                <span class="label">数量：</span>
                <el-button @click="update(item.goodid, item.number - 1)">-</el-button>
                <span class="value">{{ item.number || 0 }}</span>
                <el-button @click="update(item.goodid, item.number + 1)">+</el-button>
              </div>
              <div class="info-row">
                <span class="label">位置：</span>
                <span class="value" style="font-size: 14px">{{ item.location || '未填写' }}</span>
              </div>
              <div class="info-row">
                <span class="label">时间：</span><br>
                <span class="value">
                    {{ item.starttime || '未填写' }} —— {{ item.endtime || '未填写' }}
                  </span>
              </div>
            </div>
          </div>
        </el-card>
        <el-card class="data-card" shadow="hover" v-else>
          <div style="justify-self: end;">
            <button @click="saveEdit(item)" style="background: #0ad838;height: 25px;border-radius: 10px">
              <el-icon><Select /></el-icon>
            </button>
            <button @click="cancelEdit(item)" style="background: #de3f3f;height: 25px;border-radius: 10px">
              <el-icon ><CloseBold /></el-icon>
            </button>
          </div>
          <el-form
              :ref="(el:any) => (editForm = el)"
              :model="item"
              :rules="data.rules"
              class="card-content"
          >
            <div class="avatar-degree-group">
              <el-upload
                  class="avatar"
                  action="http://localhost:8080/upload"
                  :show-file-list="false"
                  :on-success="function(response, uploadFile){return handleAvatarSuccess(response, uploadFile,item)}"
                  :before-upload="beforeAvatarUpload"
              >
<!--               :on-success="(response, uploadFile)=>handleAvatarSuccess(response, uploadFile,item)"-->
                  <el-image
                      v-if="item.image"
                      :src="`http://localhost:8080${item.image}`"
                      class="avatar"
                  />
                <el-icon v-else class="default-avatar"><Goods /></el-icon>
              </el-upload>
              <el-form-item  label="程度" prop="degree">
              <el-rate
                  style="--el-rate-icon-size:15px;--el-rate-fill-color: #e26608"
                  v-model="item.degree"
                  :max="3"
              ></el-rate>
            </el-form-item>
            </div>
            <div class="data-info">
              <el-form-item class="info-row" label="名称" prop="name">
                <el-input v-model="item.name" placeholder="请输入名称"/>
              </el-form-item>
              <el-form-item class="info-row" label="数量" prop="number">
                <el-input v-model="item.number"/>
              </el-form-item>
              <el-form-item class="info-row" label="分类" prop="classification">
                <el-input v-model="item.classification" placeholder="请输入分类"/>
              </el-form-item>
              <el-form-item class="info-row" label="位置" prop="classification">
                <el-select style="width: 100%" v-model="item.location" placeholder="请选择位置选项">
                  <el-option
                      v-for="item in data.options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.label"
                  />
                </el-select>
              </el-form-item>
              <el-form-item class="info-row" label="结束时间" prop="endtime">
              <el-date-picker
                  v-model="item.endtime"
                  type="date"
                  placeholder="选择结束时间"
                  value-format="YYYY-MM-DD"
                  autocomplete="off"
              ></el-date-picker>
            </el-form-item>
            </div>
          </el-form>
        </el-card>
      </div>
      <div class="empty-tip" v-if="data.goods.length === 0">暂无数据</div>
    </div>
  </div>
</template>
<style scoped>
/* 【核心】卡片容器：Grid 布局（一行3个卡片） */
.card-list-container {
  padding: 20px;
  display: grid;
  grid-template-columns: repeat(3, 1fr);  /* 一行3列，自动平分宽度 */
  gap: 15px;  /* 卡片之间的间距（水平+垂直） */
  margin-bottom: 50px;
}
/* 翻转核心样式 */
.flip-container {
  perspective: 1200px;
  height: 100%;
  min-height: 270px; /* 确保容器高度足够，避免卡片被截断 */
}
.flip-container.flipped .flipper {
  transform: rotateY(180deg);
}
.flipper {
  transition: transform 0.5s ease;
  transform-style: preserve-3d;
  position: relative;
  height: 100%;
}
.star-icon {
  color: #f88626;
  font-size: 15px;
}

/* 卡片样式 */
.data-card {
  border: 1.5px solid rgba(89, 86, 81, 0.48);
  background-image: url("../assets/images/g_bg2.jpg");
  background-size: cover;
  background-position: center -25px;
  margin-bottom: 2px;
  border-radius: 8px;
  box-sizing: border-box;
  min-width: 390px;
  min-height: 270px;  /* 固定最小高度，避免卡片高度不一致 */
  transition: all 0.3s ease;
}
.data-card:first-child {
  z-index: 2; /* 正面层级高于背面，初始优先显示 */
}
.data-card:last-child {
  z-index: 1; /* 背层级低于正面 */
}
.data-card:hover {
   /* 向上悬浮更大距离（例如10px） */
   transform: translateY(-10px) ;
   /* 可选：增强阴影效果，配合悬浮感 */
   box-shadow: 0 10px 20px rgb(141, 0, 0);
   background-position: center -25px;
 }
/* 卡片内部内容布局 */
.card-content {
  display: flex;
  align-items: center;
  padding: 15px;
  gap: 15px;  /* 头像区、详情区、按钮区的间距 */
}

/* 头像+程度合并组 */
.avatar-degree-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

/* 物品图片样式（方形，适应物品场景） */
.avatar {
  width: 100px;
  height: 100px;
  object-fit: cover;  /* 图片裁剪适配，避免拉伸 */
  border-radius: 4px;  /* 小圆角，更贴合物品图片 */
}

/* 默认图标样式（调整大小和居中） */
.default-avatar {
  width: 100px;
  height: 100px;
  line-height: 100px;  /* 垂直居中图标 */
  text-align: center;
  background-color: #eaf4ff;
  color: #409eff;
  font-size: 36px;  /* 图标放大，更醒目 */
  border-radius: 4px;
}

/* 程度字段样式 */
.degree-info {
  font-size: 14px;
  font-weight: 500;  /* 加粗，突出程度信息 */
}
/* 数据详情区域 */
.data-info {
  flex: 1;  /* 占满剩余宽度 */
}
.info-row {
  width: 200px;
  margin-bottom: 6px;
  font-size: 14px;  /* 调整字体大小，避免换行 */
}
.el-input .el-date-picker{
  width: 120px;
}
.label {
  color: #606266;
  margin-right: 1px;
}
.value {
  color: #303133;
}
.el-form-item__label {
  font-size: 10px;
}
/* 操作按钮区域 */
.card-actions {
  display: flex;
  flex-direction: column;  /* 按钮纵向排列，节省空间 */
  gap: 8px;
}

/* 空数据提示（占满整行） */
.empty-tip {
  grid-column: 1 / -1;  /* Grid布局中占满所有列 */
  text-align: center;
  padding: 80px;
  color: #909399;
  background-color: #f9f9f9;
  border-radius: 8px;
}

/* 响应式适配：屏幕较小时改为一行1列 */
@media (max-width: 992px) {
  .card-list-container {
    grid-template-columns: 1fr;  /* 一行1列 */
  }
}
.el-button{
  border-radius: 15px;
  font-size: 20px;
  width: 20px;
  margin: 10px;
  background: #adc6c2;
}
</style>